package com.itisyue.fun.utils;

import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyPair;
import java.util.Base64;

public class Sm2UtilBack {
    private static Logger log = LoggerFactory.getLogger(Sm2UtilBack.class);
    /**
     * SM2公钥加密
     *
     * @param rawStr    数据字符串
     * @param publicKey 公钥字字符串
     * @return 加密之后的数据字字符串
     */
    public static String encrypt(String rawStr, String publicKey) throws Exception {
        SM2 sm2 = SmUtil.sm2(null, publicKey);
        sm2.setMode(SM2Engine.Mode.C1C2C3);
        return sm2.encryptBase64(rawStr, KeyType.PublicKey);
    }

    /**
     * SM2私钥解密
     *
     * @param rawStr     数据字字符串
     * @param privateKey 私钥字字符串
     * @return 解密之后的数据字符数组
     */
    public static String decrypt(String rawStr, String privateKey) throws Exception {
        SM2 sm2 = SmUtil.sm2(privateKey, null);
        sm2.setMode(SM2Engine.Mode.C1C2C3);
        return sm2.decryptStr(rawStr, KeyType.PrivateKey);
    }

    public static void generateSM2Key(){
        KeyPair keyPair = KeyUtil.generateKeyPair("SM2");
        String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
//        String publicKey = Base64Utils.encodeToString(keyPair.getPublic().getEncoded());
//        String privateKey = Base64Utils.encodeToString(keyPair.getPrivate().getEncoded());
        System.out.println("sm2公钥: " + publicKey);
        System.out.println("sm2私钥: " + privateKey);
    }

    public static String jiamiTest(String businessType, String businessId, String userName,String queryUrl) throws Exception{
        log.info("businessType={}, businessId={}, userName={}, queryUrl={}", businessType, businessId, userName, queryUrl);
        String publicKey  = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEWuTGiihcA0P09ansdBX0X7R2OOACTEsRYwpUc97r8yq4iIHvM2MjklumD8wJQvdDMjsSMUdwmWGjHm8r11bZgQ==";
        long time = System.currentTimeMillis();

        //String str = "{\"businessType\":\"jcmq\",\"businessId\":\"0000004774\",\"queryUrl\":\"http://195.203.29.90:8084/services-assist/queryCustomerById.json\",\"timestamp\": "+time+"}";
        String str = "{\"businessType\":\""+businessType+ "\",\"businessId\":\""+businessId+"\",\"userName\":\""+userName+"\",\"queryUrl\":\""+queryUrl+"\",\"timestamp\": "+time+"}";
        String encrypt = encrypt(str, publicKey);
        String encodeToUrlSafeString = Base64.getUrlEncoder().encodeToString(encrypt.getBytes());
//        String encodeToUrlSafeString = Base64Utils.encodeToUrlSafeString(encrypt.getBytes());
        return encodeToUrlSafeString;
    }

    public static void jiemiTest() throws Exception{
        String privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQg24NVBZF1n4WtXwr8fr43IGP79oPGzMR9zJO19MGuazSgCgYIKoEcz1UBgi2hRANCAARa5MaKKFwDQ/T1qex0FfRftHY44AJMSxFjClRz3uvzKriIge8zYyOSW6YPzAlC90MyOxIxR3CZYaMebyvXVtmB";

        String token = "Qk1BQkNEVGNyb2J6czd3R1JENUJwZnlYTm9IdG5YUEFydnBEdTE0QWxjbS9NeEFiNVRMUVJvQ1lOSnhLQXJKUFhxVVY1cGNOYmxPRHg0cC9vakNKQlFHN3U0Rjlub01EOVU0cmVCMEVsaXRGeWZnS2lLZXBsTXFTQTBtYjdaY1o0OUIyTCszWG1uSFA0WFlHNktpRW5ySGZzMmgvMzhNT05zUVBqZWxlVm5GeCs1bHNpbHpaTFpGTWg0ZkNJemR0WmV2UWJkRFYvd3pyZnBQK2xFS1JpcFozSU1iL012UVFhdnBSUTdlU1NhMTUwVzVCanVXRmRJUUJUa09qaE1VQlRYUWxQQ3A2OTl2Y2pEUW5Mai9sZWZneG54dDlpSUZRbGJCaXBJZ0JjbkxYUGRsRUVqRFQ5a3FtQlZxS0tTcnJ4dzVIS1UvTVluM2c5Zz09";
        // 解密token
        byte[] decodeFromUrlSafeString = Base64.getUrlDecoder().decode(token);
//        byte[] decodeFromUrlSafeString = Base64Utils.decodeFromUrlSafeString(token);
        String TOKENDecrypt = Sm2UtilBack.decrypt(new String(decodeFromUrlSafeString), privateKey);
        System.out.println("解密后的明文：" + TOKENDecrypt);

        String str = "BDHFklcvp7bC2aHpB6wdSb+0fvyzxINIUp6/txDhjQ0Ai3soWsNMDi6xhetxUP9VGCRQjMIyOzVBWUQx2EHwIrOdM1mL9Vxv8gTepzYMlVo3nbyOZAuYMVIbGvy1fIOxtwZ1Rw==";
        String decrypt = decrypt(str, privateKey);
//        System.out.println("解密后的明文：" + decrypt);
    }

    public static void main(String[] args) throws Exception{
//        String localUrl = "/home/nasdisk/ecl/test-script/230214112813873000.mp4";
//        String localUrl = "/home/nasdisk/ecl/test-script/11.mp3";
        String localUrl = "/home/nasdisk/ecl/test-script/11.mp4";
        String publicKey = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEWuTGiihcA0P09ansdBX0X7R2OOACTEsRYwpUc97r8yq4iIHvM2MjklumD8wJQvdDMjsSMUdwmWGjHm8r11bZgQ==";
        String s = EncryptUtil.fileDownloadEncrypt(localUrl, publicKey);
        System.out.println(s);

//        jiemiTest();

//        for(int i=0;i<100;i++){
//            Thread thread = new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try{
//                        String publicKey = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEWuTGiihcA0P09ansdBX0X7R2OOACTEsRYwpUc97r8yq4iIHvM2MjklumD8wJQvdDMjsSMUdwmWGjHm8r11bZgQ==";
//                        Sm2Util.encrypt("123445656", publicKey);
//                    }catch (Exception e){
//                        log.error("", e);
//                    }
//
//                }
//            });
//            thread.start();
//        }
//        Thread.sleep(10000000);


    }
}
